package com.yuyou.activity.group.service.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.activity.group.service.entity.ActivityGroup;
import com.yuyou.activity.group.service.entity.ActivityGroupUser;
import com.yuyou.activity.group.service.mapper.ActivityGroupMapper;
import com.yuyou.activity.group.service.service.IActivityGroupService;
import com.yuyou.activity.group.service.service.IActivityGroupUserService;
import com.yuyou.activity.group.service.vo.req.ReqAttendActivityGroup;
import com.yuyou.activity.group.service.vo.resp.RespActivityGroupDetail;
import com.yuyou.activity.group.service.vo.resp.RespActivityGroupDetailPhone;
import com.yuyou.activity.group.service.vo.resp.RespCanActivityGroupList;
import com.yuyou.activity.util.bean.ResBoolSimpleInfo;
import com.yuyou.activity.util.util.DateUtil;
import com.yuyou.activity.util.util.DefindBeanUtils;
import com.yuyou.activity.util.util.PhoneUtil;
import com.yuyou.activity.util.util.Sequence;
import com.yuyou.activity.util.util.SpringUtil;


@Service
public class ActivityGroupServiceImpl implements IActivityGroupService{

	@Autowired
	private ActivityGroupMapper activityGroupMapper;
	@Autowired
	private IActivityGroupUserService activityGroupUserService;
	
	@Override
	public int deleteByPrimaryKey(Long activityGroupId) {
		return activityGroupMapper.deleteByPrimaryKey(activityGroupId);
	}

	@Override
	public int insert(ActivityGroup record) {
		if(record.getActivityGroupId()==null){
			record.setActivityGroupId(Sequence.getSequence().nextId());			
		}
		if(record.getCreateTime()==null){
			record.setCreateTime(new Date());			
		}
		return activityGroupMapper.insert(record);
	}

	@Override
	public ActivityGroup selectByPrimaryKey(Long activityGroupId) {
		return activityGroupMapper.selectByPrimaryKey(activityGroupId);
	}

	@Override
	public int updateByPrimaryKeySelective(ActivityGroup record) {
		return activityGroupMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<RespCanActivityGroupList> findCanActivityGroup(String projectCode) {		
		List<RespCanActivityGroupList> list=activityGroupMapper.findCanActivityGroup(projectCode);
		list.forEach(item->{
			item.setPhone(PhoneUtil.tran4star(item.getPhone()));	
			List<ActivityGroupUser> activityGroupUserList=activityGroupUserService.findByActGroId(item.getActivityGroupId());
			item.setAttend(activityGroupUserList.size());
		});
				
		return list;
	}
	
	@Override
	public List<RespCanActivityGroupList> findMoreCanActivityGroup(String projectCode,int limit) {		
		List<RespCanActivityGroupList> list=activityGroupMapper.findMoreCanActivityGroup(projectCode,limit);
		list.forEach(item->{
			item.setPhone(PhoneUtil.tran4star(item.getPhone()));	
			List<ActivityGroupUser> activityGroupUserList=activityGroupUserService.findByActGroId(item.getActivityGroupId());
			item.setAttend(activityGroupUserList.size());
		});

		list.sort(Comparator.comparing(RespCanActivityGroupList::getAttend).reversed().thenComparing(RespCanActivityGroupList::getCloseTime));
			
		return list;
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<RespActivityGroupDetail> attendActivityGroup(
			ReqAttendActivityGroup reqAttendActivityGroup) throws Exception {
		 ResBoolSimpleInfo<RespActivityGroupDetail> res=new ResBoolSimpleInfo<RespActivityGroupDetail>();
		 
		//配置
		Environment env=(Environment)SpringUtil.getBean("environment");
		//人数限制
		String _num=env.getProperty(reqAttendActivityGroup.getProjectCode()+"_num");
		//禁止开团时间
		String _openClose=env.getProperty(reqAttendActivityGroup.getProjectCode()+"_openClose");
		//结束时间设定
		String _closeHour=env.getProperty(reqAttendActivityGroup.getProjectCode()+"_closeHour");
			
		//查询是否已经参与活动
		ActivityGroupUser active=activityGroupUserService.findActiveGroupByPhone(reqAttendActivityGroup.getProjectCode(),reqAttendActivityGroup.getPhone());		
		if(active!=null){
			ResBoolSimpleInfo<RespActivityGroupDetail> activeRes=this.activityGroupDetailById(reqAttendActivityGroup.getProjectCode(), active.getActivityGroupId());
			activeRes.setMessage("你已经参与过活动！");
			activeRes.setSuccess(false);
			return activeRes;
		}
		
		
		Long activityGroupId=null;
		
				
		//团主还是团员
		if(reqAttendActivityGroup.getActivityGroupId()==null){			
			
			Date _openCloseD=DateUtil.parseDateByPattern(_openClose, DateUtil.yyyyMMddHHmmss);
			if(_openCloseD.getTime()<new Date().getTime()){
				res.setMessage("不能开团！");
				res.setSuccess(false);
				return res;
			}
			
			//拼团ID
			activityGroupId=Sequence.getSequence().nextId();
			//用户ID
			Long activityGroupUserId=Sequence.getSequence().nextId();
			
			ActivityGroup newActivityGroup=new ActivityGroup();
			newActivityGroup.setActivityGroupId(activityGroupId);
			newActivityGroup.setPhone(reqAttendActivityGroup.getPhone());
			newActivityGroup.setProjectCode(reqAttendActivityGroup.getProjectCode());
			newActivityGroup.setStatus(0);
			newActivityGroup.setTotal(Integer.parseInt(_num));
			newActivityGroup.setType(1);
			newActivityGroup.setCreateUser(activityGroupUserId);
			
			Date now=new Date();
			newActivityGroup.setCreateTime(now);
			
			//设置结束时间
			Calendar cal = Calendar.getInstance();   
	        cal.setTime(now);   
	        cal.add(Calendar.HOUR, Integer.parseInt(_closeHour));
	        Date closeDate = cal.getTime();  		
			newActivityGroup.setCloseTime(closeDate);
			
			this.insert(newActivityGroup);	
			res=addUser(Integer.parseInt(_num),reqAttendActivityGroup,activityGroupId,activityGroupUserId);
		}else{
			
			//假如活动已经结束，不能参团
			ActivityGroup actClose=this.selectByPrimaryKey(reqAttendActivityGroup.getActivityGroupId());
			if(actClose.getStatus()!=0){
				res.setMessage("来晚了，该团已成团！请点击“参加其他团”，返回首页开团！");
				res.setSuccess(false);
				return res;
			}	
			
			activityGroupId=reqAttendActivityGroup.getActivityGroupId();
			res=addUser(Integer.parseInt(_num),reqAttendActivityGroup,activityGroupId,null);
		}		
		if(res.isSuccess()){
			return this.activityGroupDetailById(reqAttendActivityGroup.getProjectCode(), activityGroupId);
		}		
		return res;
	}

	/**
	 * 新增拼团用户
	 * @param reqAttendActivityGroup
	 * @param activityGroupId
	 * @return
	 */
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<RespActivityGroupDetail> addUser(int _num,ReqAttendActivityGroup reqAttendActivityGroup,Long activityGroupId,Long activityGroupUserId){
		ResBoolSimpleInfo<RespActivityGroupDetail> res=new ResBoolSimpleInfo<RespActivityGroupDetail>();	
				
		//参团有人数限制
		//总人数
		ActivityGroup activityGroup=this.selectByPrimaryKey(activityGroupId);
		
		//已经参加人数
		List<ActivityGroupUser> activityGroupUserList=activityGroupUserService.findByActGroId(activityGroupId);
		if(activityGroupUserList.size()+1>activityGroup.getTotal()){
			res.setMessage("来晚了，该团已成团！请点击“参加其他团”，返回首页开团！");
			res.setSuccess(false);
			return res;
		}else if(activityGroupUserList.size()+1>=activityGroup.getTotal()){
			//满团则更新状态
			ActivityGroup upActivityGroup=new ActivityGroup();
			upActivityGroup.setActivityGroupId(activityGroupId);
			upActivityGroup.setStatus(1);
			this.updateByPrimaryKeySelective(upActivityGroup);
		}
			
		ActivityGroupUser newActivityGroupUser=new ActivityGroupUser();
		
		if(reqAttendActivityGroup.getActivityGroupId()!=null){						
			newActivityGroupUser.setType(1);				
		}else{
			//开团
			newActivityGroupUser.setType(0);
		}
		
		if(activityGroupUserId!=null){
			newActivityGroupUser.setActivityGroupUserId(activityGroupUserId);
		}
		
		newActivityGroupUser.setActivityGroupId(activityGroupId);
		newActivityGroupUser.setIsNotice(0);
		newActivityGroupUser.setName(reqAttendActivityGroup.getName());
		newActivityGroupUser.setPhone(reqAttendActivityGroup.getPhone());
		newActivityGroupUser.setProjectCode(reqAttendActivityGroup.getProjectCode());
		newActivityGroupUser.setSchoolId(reqAttendActivityGroup.getSchoolId());
		newActivityGroupUser.setSchoolName(reqAttendActivityGroup.getSchoolName());
		
		activityGroupUserService.insert(newActivityGroupUser);
		
		res.setSuccess(true);
		return res;
		
	}
	
	@Override
	public ResBoolSimpleInfo<RespActivityGroupDetail> canAttActGro(String projectCode,String phone) {
		ResBoolSimpleInfo<RespActivityGroupDetail> res=new ResBoolSimpleInfo<RespActivityGroupDetail>();		
		ActivityGroupUser active=activityGroupUserService.findActiveGroupByPhone(projectCode,phone);
		if(active!=null){
			ResBoolSimpleInfo<RespActivityGroupDetail> activeRes=this.activityGroupDetailById(projectCode, active.getActivityGroupId());
			activeRes.setMessage("你已经参与过活动！");
			activeRes.setSuccess(false);
			return activeRes;
		}
		res.setSuccess(true);
		return res;
	}

	@Override
	public ResBoolSimpleInfo<RespActivityGroupDetail> activityGroupDetail(
			String projectCode,String phone) {
		
		ResBoolSimpleInfo<RespActivityGroupDetail> res=new ResBoolSimpleInfo<RespActivityGroupDetail>();
		RespActivityGroupDetail detail=new RespActivityGroupDetail();
		
		//找出用户
		ActivityGroupUser activityGroupUser=activityGroupUserService.selectByCode7Phone(projectCode, phone);
		if(activityGroupUser!=null){
			//拼图活动
			ActivityGroup activityGroup=this.selectByPrimaryKey(activityGroupUser.getActivityGroupId());
			
			//所有团员
			List<RespActivityGroupDetailPhone> userList=new ArrayList<RespActivityGroupDetailPhone>();
			List<ActivityGroupUser> activityGroupUserList=activityGroupUserService.findByActGroId(activityGroup.getActivityGroupId());
			activityGroupUserList.forEach(item -> {
				RespActivityGroupDetailPhone user =new RespActivityGroupDetailPhone();
				DefindBeanUtils.copyProperties(item, user);
				user.setPhone(PhoneUtil.tran4star(user.getPhone()));				
				userList.add(user);
			});
					
			detail.setStatus(activityGroup.getStatus());
			detail.setTotal(activityGroup.getTotal());
			detail.setCloseTime(activityGroup.getCloseTime());
			detail.setUserList(userList);
			detail.setActivityGroupId(activityGroup.getActivityGroupId());
			
		}else{
			res.setSuccess(false);
			res.setMessage("没有该手机号码信息！");
			return res;
		}
		res.setData(detail);
		res.setSuccess(true);
		return res;
		
	}

	@Override
	public void updateFailActivity() {
		activityGroupMapper.updateFailActivity();
	}

	@Override
	public ResBoolSimpleInfo<RespActivityGroupDetail> activityGroupDetailById(
			String projectCode, Long activityGroupId) {
		
		ResBoolSimpleInfo<RespActivityGroupDetail> res=new ResBoolSimpleInfo<RespActivityGroupDetail>();
		RespActivityGroupDetail detail=new RespActivityGroupDetail();
		
		//拼图活动
		ActivityGroup activityGroup=this.selectByPrimaryKey(activityGroupId);
		
		//所有团员
		List<RespActivityGroupDetailPhone> userList=new ArrayList<RespActivityGroupDetailPhone>();
		List<ActivityGroupUser> activityGroupUserList=activityGroupUserService.findByActGroId(activityGroup.getActivityGroupId());
		activityGroupUserList.forEach(item -> {
			RespActivityGroupDetailPhone user =new RespActivityGroupDetailPhone();
			DefindBeanUtils.copyProperties(item, user);
			user.setPhone(PhoneUtil.tran4star(user.getPhone()));				
			userList.add(user);
		});
				
		detail.setStatus(activityGroup.getStatus());
		detail.setTotal(activityGroup.getTotal());
		detail.setCloseTime(activityGroup.getCloseTime());
		detail.setUserList(userList);
		detail.setActivityGroupId(activityGroup.getActivityGroupId());
		
		res.setData(detail);
		res.setSuccess(true);
		return res;
	}

}
